<template>
    <div>
        <!-- 头部 -->
        <header class="w-34 py-5 w-[25rem] flex items-center">
            <n-input placeholder="关键字搜索" style="width: 20rem" v-model:value="keyword">
                    <template #prefix>
                        <n-icon :component="FlashOutline" />
                    </template>
             </n-input>
             <n-button class="ml-2" type="success" @click="SearchList">搜索</n-button>
        </header>
        <!-- 表格 -->
        <n-data-table
            striped 
            ref="tableRef"
            :columns="columns"
            :data="NewList"
            :bordered="true"
            :pagination="paginationReactive"
        />
    </div>
    <!-- 预览发布的新闻 -->
    <n-drawer
        v-model:show="showOuter"
        placement="top"
        resizable
        height="100%"
    >
        <n-drawer-content>
        <template #header>
                <header class="flex justify-between items-center">
                    <n-space>
                        <n-button strong secondary :type="list_type? 'tertiary': 'success'" @click="doChangeType">中文新闻</n-button>
                        <n-button strong secondary :type="list_type? 'success': 'tertiary'" @click="doChangeType">英文新闻</n-button>
                    </n-space>
                    <n-gradient-text type="error" @click="showOuter = false">
                    关闭预览
                    </n-gradient-text>
                </header>
        </template>
        <template #default>
            <main class="w-3/4 mx-auto flex sm:max-lg:w-full sm:max-lg:px-3 relative">
                <!-- 新闻内容 -->
                <div class="w-[60%] mr-20 md:max-xl:mr-10 sm:max-md:w-full sm:max-md:mr-0 lg:max-xl:w-[70%] pb-10">
                    <HomeNews/>
                        <div id="news_container" class="w-full bg-white" v-html="previewContent.zh_body" v-if="!list_type">
                        </div>
                    <HomeNews/>
                </div>
                <!-- 侧边导航栏 -->
                <div class="flex-1 h-auto sm:max-md:hidden relative">
                    <div class="sticky top-[3rem] left-0">
                        <header class="text-black text-xl pb-5 border-b-2 font-bold md:max-lg:text-lg" style="border-color: #ddd;">推荐新闻</header>
                        <ul class="w-full">
                            <li class="w-full h-[8rem] border-b-2 flex flex-col justify-center" style="border-color: #ddd;" v-for="item in NewList.slice(0,4)" :key="item.id">
                                <time class="text-base md:max-xl:text-sm text-slate-600">{{ dayjs(item.createdAt).format('YYYY-MM-DD') }}</time>
                                <p class="text-base pt-2 mt-3 md:max-xl:text-sm">{{ item.zh_title }}</p>
                            </li>
                        </ul>
                    </div>
                </div>
            </main>
        </template>
        </n-drawer-content>
    </n-drawer>

    <!-- 编辑新闻 -->
    <n-drawer 
        v-model:show="editListVisable"
        placement="top"
        resizable
        height="100%"
        :z-index="19"
    >
      <n-drawer-content>
        <template #header>
            <header class="flex justify-between items-center">
                <n-space>
                    <n-button strong secondary :type="edit_type? 'tertiary': 'success'" @click="editChangType">编辑新闻</n-button>
                    <n-button strong secondary :type="edit_type? 'success': 'tertiary'" @click="editChangType">添加英文版</n-button>
                </n-space>
                <n-gradient-text type="error" @click="editListVisable = false">
                    退出编辑
                </n-gradient-text>
            </header>
        </template>
        <template #default>
            <main>
                <template v-if="!edit_type">
                    <edit v-model:cover="editviewContent.cover" v-model:title="editviewContent.zh_title" :news_id="editviewContent.news_id" v-model:value="editviewContent.zh_body" v-model:desc="editviewContent.zh_desc" ></edit>
                </template>
                <template v-else>
                    <edit v-model:cover="editviewContent.cover" v-model:title="editviewContent.zh_title" :news_id="editviewContent.news_id" v-model:value="editviewContent.zh_body" v-model:desc="editviewContent.zh_desc" :btn="false"></edit>
                </template>
            </main>
        </template>
      </n-drawer-content>
    </n-drawer>
</template>

<script setup lang="ts">
    import dayjs from 'dayjs'
    import { NButton, NIcon,NImage,NPopconfirm, NSwitch, NTag } from 'naive-ui';
    import { getCurrentInstance, render } from 'vue';
    import {Globe,Backspace,Create, Search} from '@vicons/ionicons5'
    import { ref,onMounted,reactive } from 'vue'
    let { proxy } = getCurrentInstance()
    let NewList = ref([]) //新闻列表
    import HomeNews from '../../components/homeNews.vue'
 
    // 生命周期
    onMounted(()=>{
        getNewsList()
    })
    /**
     * 数据渲染
     */
    let tableRef = ref()
    const columns = [
        {
            title: '新闻编号',
            key: 'news_id',
            width: '5%',
            align: 'center'
        },
        { 
            title: '新闻封面', 
            key: 'cover',
            width: '10%',
            align: 'center',
            render(row) {
                return h(NImage, {
                    src: row.cover,
                    lazy: true,
                    style: {
                        width: '100%',
                        height: '100%'
                    }
                })
            }

         },
        { title: '新闻标题', key: 'zh_title', width: '20%', align: 'center' },
        { 
            title: '新闻描述', 
            key: 'zh_desc', 
            align: 'center', 
            width: '20%',
            ellipsis: {
                tooltip: true
            } 
        },
        {
            title: '新闻类型',
            key: 'tag',
            width: '10%',
            align: 'center',
            render(row:any) {
                let tag:string = row.tag as string
                switch(tag) {
                    case '产品':
                        return h(NTag, { type: 'info' }, () => tag)
                    case '客户案例':
                        return h(NTag, { type: 'success' }, () => tag)
                    case '展会':
                        return h(NTag, { type: 'warning' }, () => tag)
                    default:
                        return h(NTag, { type: 'error' }, () => tag)
                }
            }
        },
        {
            title: '是否发布',
            key: 'status',
            width: '5%',
            align: 'center',
            render(row) {
                return h(NSwitch,{
                    value: row.status,
                    onUpdateValue: async (value) => {
                        let id:number = row.news_id // 新闻编号
                        let res = await proxy.$http.put(`/list/status/${id}`, {status: value})
                        if (res.data.code !== 200) return proxy.$message.error("修改失败")
                        proxy.$message.success("修改成功")
                        getNewsList()
                    }
                }
            )
            },
        },
        { 
            title: '发布时间',
             key: 'createdAt',
              width:'10%',
               align: 'center',
               defaultSortOrder: 'descend',
               sorter: 'default',
               render(row) {
                return dayjs(row.createdAt).format('YYYY-MM-DD HH:mm:ss')
            }
        }, 
        { title: '操作', key: 'action', width: '240px', align: 'center',render(row) {
            return h('div', 
            {
                style: { display: 'flex', justifyContent: 'center' }
            },
            [
            h(NButton, {
                    type: 'info',
                    size: 'small',
                    onClick:() => {
                        doEditList(row)
                    },
                    style: {
                        marginRight: '10px'
                    },
                },
                {
                    default: () => h('div',{style: {display: 'flex',alignItems: 'center'}},[
                        h(NIcon,{size:16,component: Create,color: '#fff'}),
                        h('span',{style: {marginLeft: '5px'}},'编辑')
                    ])
                }),
                h(NPopconfirm,{
                        onPositiveClick: async () => {
                        let id:number = row.news_id // 用户留言编号
                        handlePositiveClick(id)
                    },
                    onNegativeClick: () => {
                        proxy.$message.info("取消删除")
                    }
                },{
              trigger: () => h(NButton,{ type: 'error',size: 'small'},[
                h(NIcon,{size:16,component: Backspace,color: '#fff'}),
                h('span',{style: {marginLeft: '5px'}},'删除')
            ]),
              default: () => h(
              'div', 
              '确定删除吗？',
            )
            }),
                h(NButton, {
                    type: 'warning',
                    size: 'small',
                    onClick:() => {
                        doShowOuter(row)
                    },
                    style: {
                        marginLeft: '10px'
                    },
                },
                {
                    default: () => h('div',{style: {display: 'flex',alignItems: 'center'}},[
                        h(NIcon,{size:16,component: Globe,color: '#fff'}),
                        h('span',{style: {marginLeft: '5px'}},'预览')
                    ])
                })
            ])
        }}
    ]
    let keyword = ref('')
    const SearchList = () => {
        console.log(tableRef.value)
        tableRef.value.filter({
            zh_title: [keyword.value],
        })
    }
    // 获取新闻列表
    const getNewsList = async () => {
        let res = await proxy.$http.get("/list")
        NewList.value = res.data.data
    }

    // 确认删除
    const handlePositiveClick = async (id) => {
        let res = await proxy.$http.delete(`/list/del/${id}`)
        if(res.data.code === 200){
            proxy.$message.success("删除成功")
            getNewsList()
        }
    }
    // 取消删除
    const handleNegativeClick = () => {
        proxy.$message.info("已取消删除")
    }

    // 修改新闻的状态
    const doChangeStatus = async (id:number,status:number) => {
       const res = await proxy.$http.put(`/list/status/${id}`,{status}) 
       if (res.data.code !==200) return proxy.$message.error("修改失败")
       proxy.$message.success("修改成功")
    }

    /**
     * 新闻的预览
     *
     */
    const showOuter = ref<boolean>(false)
    let previewContent = ref('') // 预览内容
    let editviewContent = ref("") // 编辑的内容
    let list_type = ref(false) // 文章类型 false => 中文 true => 英文
    // 打开预览
    const doShowOuter = (item:any) => {
      showOuter.value = true
      previewContent.value = item
    }

    // 切换中英文
    const doChangeType = () => {
        if (!previewContent.value.en_body) return proxy.$message.warning("暂无英文新闻,请去编辑添加")
        list_type.value = !list_type.value
    }

    /**
     * 编辑新闻
     */
    import edit from '@/components/editor.vue'
    let edit_type = ref(false) // false => 编辑新闻 true => 添加英文版
    const editListVisable = ref(false)
    const doEditList = (item) => {
        editviewContent.value = item
        editListVisable.value = true
    }

    const editChangType = () => {
        edit_type.value = !edit_type.value
    }

    /**
     * 分页操作
     */
     const paginationReactive = reactive({
      page: 1,
      pageSize: 3,
      showSizePicker: true,
      pageSizes: [3, 5, 7],
      onChange: (page: number) => {
        paginationReactive.page = page
      },
      onUpdatePageSize: (pageSize: number) => {
        paginationReactive.pageSize = pageSize
        paginationReactive.page = 1
      }
    })
    const pageCount = ref(3)
    const page = ref(1)
    const pageSize = ref(3)
    const pageSizes = [
        {
            label: "3 每页",
            value: 10
        },
        {
            label: "5 每页",
            value: 15
        }
    ]
    import {FlashOutline} from '@vicons/ionicons5'
    import { h } from 'vue';
    // 页码数量改变
    const doPageChange = (page:number) => {
        console.log(page)
    }
    // 页码长度改变
    const doPageSizeChange = (size:number) => {
        console.log(size)
    }

</script>

<style lang="less" scoped>
    :deep(.n-data-table__pagination) {
        display: flex;
        justify-content: center;
    }
    :deep(.n-drawer-header__main) {
        width: 100%!important;
    }
    :deep(.MsoNormal) {
        display: flex;
        justify-content: center;
    }
    :deep(.n-pagination) {
        display: flex;
        justify-content: center;
    }
</style>